package com.mycompany.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.mycompany.entity.Rule;
import com.mycompany.repository.RuleDao;

@Repository
public class RuleDaoImpl implements RuleDao {
	
	private EntityManager em;
	String sqlQuery="";
	

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public void persist(Rule rule) {
		em.persist(rule);
	}

	@Override
	public void merge(Rule rule) {
		em.merge(rule);
	}

	@Override
	public void remove(Rule rule) {
		rule.setActiveFlg(false);
		em.merge(rule);
	}

	@Override
	public Rule findById(Integer ruleId) {
		sqlQuery = "select x from Rule x where x.ruleId= :ruleId and x.activeFlg = 1";
		return (Rule) em.createQuery(sqlQuery).setParameter("ruleId", ruleId).getSingleResult();
	}

	@Override
	public Rule find(Rule rule) {
		sqlQuery = "select x from Rule x where x.ruleId= :ruleId and x.activeFlg = 1";
		return (Rule) em.createQuery(sqlQuery).setParameter("ruleId", rule.getRuleId()).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Rule> findAll() {
		sqlQuery = "select x from Rule x where x.activeFlg = 1 ORDER BY x.ruleId DESC ";
        return em.createQuery(sqlQuery).getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Rule> findListByCodition(Rule rule) {
		sqlQuery = "select x from Rule x where 1=1  and x.activeFlg = 1  ";
        
        if(rule.getName() != null ){
			sqlQuery = sqlQuery+" AND x.name = '"+rule.getName()+"' ";
		}
		sqlQuery = sqlQuery+ "  ORDER BY x.ruleId DESC  "; 
        return em.createQuery(sqlQuery).getResultList(); 
	}

}
